package com.itqf.interceptor;

import com.itqf.pojo.Permission;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * projectName: rbacgp8
 *
 * @author: 赵伟风
 * time: 2021/8/12 14:51
 * description:
 */
public class PermissionInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取目标访问的资源
        String targetUrl = request.getRequestURI();

        //2.匿名资源校验

        Properties  anonymity = (Properties) request.getServletContext().getAttribute("anonymity");

        if (anonymity.contains(targetUrl)) {
            //只要是匿名资源,授权结束放行!
            return true;
        }

        //3.认证资源校验
        Properties  authentication = (Properties) request.getServletContext().getAttribute("authentication");

        Map<String,Object> data = (Map<String, Object>) request.getSession().getAttribute("data");

        //到此处,只有认证和授权资源,都要求认证通过
        if (data == null) {

            //提示认证页面
            response.sendRedirect("/user/unauthentication");
            return false;
        }

        if (authentication.contains(targetUrl)){
            //是认证资源
            //并且认证通过了
            return true;
        }

        //4.授权资源校验

        List<Permission> permissions = (List<Permission>) data.get("permissions");

        int flag = 0;

        for (Permission permission : permissions) {
            if (permission.getpUrl().equalsIgnoreCase(targetUrl)) {
                flag = 1;
                break;
            }
        }

        if (flag == 0)
        {

            request.getSession().setAttribute("targetUrl", targetUrl);
            response.sendRedirect("/user/unauthorization");
            return false;
        }


        return true;
    }
}
